//
//  Plist.m
//  XRmenu
//
//  Created by shrek on 11-11-23.
//  Copyright 2011年 foxhis. All rights reserved.
//

#import "Plist.h"


@implementation Plist


+(NSDictionary *)loadFromFile:(NSString *)FileName {
	// Look in Documents for an existing plist file
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *myPlistPath = [documentsDirectory stringByAppendingPathComponent: 
							 [NSString stringWithFormat: @"%@.plist", FileName] ];
	[myPlistPath retain];
	
	// If it's not there, copy it from the bundle
	NSFileManager *fileManger = [NSFileManager defaultManager];
	if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
		NSString *pathToSettingsInBundle = [[NSBundle mainBundle] 
											pathForResource:FileName ofType:@"plist"];
		NSError *error = nil;
		[fileManger copyItemAtPath:pathToSettingsInBundle toPath:myPlistPath error:&error];
		if (error!=nil) {
			DebugLog(@"%@",[error localizedDescription]);
		}
	}		
	
	NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: myPlistPath];
	[myPlistPath release];
	NSMutableDictionary *r = plist;
	return r;  
	
}

//将数据写入文件
+(void)saveToFile:(NSString *)plistName Data:(NSDictionary *)data {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *myPlistPath = [documentsDirectory stringByAppendingPathComponent: 
							 [NSString stringWithFormat: @"%@.plist", plistName] ];
	[myPlistPath retain];
	
	// If it's not there, copy it from the bundle
	NSFileManager *fileManger = [NSFileManager defaultManager];
	if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
		NSString *pathToSettingsInBundle = [[NSBundle mainBundle] 
											pathForResource:plistName ofType:@"plist"];
		NSError *error = nil;
		[fileManger copyItemAtPath:pathToSettingsInBundle toPath:myPlistPath error:&error];
		if (error!=nil) {
			DebugLog(@"%@",[error localizedDescription]);
		}
	}		
	
	NSString *error =nil;
	
	NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:data
																   format:NSPropertyListXMLFormat_v1_0
														 errorDescription:&error];
    if(plistData) {
        [plistData writeToFile:myPlistPath atomically:YES];
    }
    else {
        NSLog(@"%@",error);
        [error release];
    }
	
	[myPlistPath release];
	
}

@end
